package com.example.easypoi.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import com.example.easypoi.config.CommonResult;
import com.example.easypoi.model.ExcelPoi;
import com.example.easypoi.service.ExcelPoiService;
import com.example.easypoi.util.ExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description:
 * @author: 朱超
 * @createDate: 2022/1/20
 * @version: 1.0
 * @remark：备注
 */
@RestController
@RequestMapping("/excel")
public class ExcelPoiController {
    @Autowired
    private ExcelPoiService excelPoiService;
    @Autowired(required = false)
    private HttpServletResponse response;

    @Autowired(required = false)
    private IExcelVerifyHandler excelVerifyHandler;

    /**
     * 导出1 使用本身代码  导出须校验的数据集
     */
    @GetMapping("/excelPoiList")
    public String ExcelPoiList() {
        ModelMap map = new ModelMap();
        //数据库数据
        List<ExcelPoi> excelPoi = excelPoiService.ExcelPoiList();
        //导出基本信息配置
        ExportParams params = new ExportParams("用户列表1312", "用户列表1312", ExcelType.XSSF);
        params.setFreezeCol(2);//冻结的列
        /**excel文件要导出的数据*/
        map.put(NormalExcelConstants.DATA_LIST, excelPoi);
        /**excel文件导出的实体*/
        map.put(NormalExcelConstants.CLASS, ExcelPoi.class);
        /**excel文件参数*/
        map.put(NormalExcelConstants.PARAMS, params);
        /**excel文件名称*/
        map.put(NormalExcelConstants.FILE_NAME, "用户列表1312");
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }

    /**
     * 导出2  使用网上excel导出导入工具类  无需校验的导入导出
     *
     * @param response
     */

    @RequestMapping(value = "/export")
    public void exportExcel(HttpServletResponse response) throws IOException {

        List<ExcelPoi> excelPoi = excelPoiService.ExcelPoiList();
        ExcelUtils.exportExcel(excelPoi, "用户信息表", "用户信息", ExcelPoi.class, "用户信息", response);
    }


    /**
     * 文件校验导入
     *
     * @return
     */
    @RequestMapping("/import2")
    public CommonResult upload(MultipartFile file) throws Exception {
        return CommonResult.success(excelPoiService.addUser(file));
    }


    @RequestMapping("/imp")
    public CommonResult uploadss(MultipartFile file) throws Exception {

        Map<String, Object> map = new HashMap<>();
        //导入的基本配置
        ImportParams params = new ImportParams();
        //表头一行
        params.setHeadRows(1);
        //标题一行
        params.setTitleRows(1);
        //代表导入这里是需要验证的（根据字段上的注解）
//        params.setNeedVerify(true);
        //设及一个自定义校验 （自定义校验名字不可重复）
        params.setVerifyHandler(excelVerifyHandler);
        //使用框架自身导入工具
        ExcelImportResult<ExcelPoi> result = ExcelImportUtil.importExcelMore(file.getInputStream(), ExcelPoi.class, params);
        //导入成功的数据
        List<ExcelPoi> list = result.getList();
        //失败结果集
        List<ExcelPoi> failList = result.getFailList();

        //拿到导出失败的工作簿
        Workbook failWorkbook = result.getFailWorkbook();
        try {
            if (result.isVerifyFail()) {
                ServletOutputStream fos = response.getOutputStream();
                //mime类型
//                  response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                  response.setHeader("Content-disposition", "attachment;filename=error.xlsx");
//                  result.getFailWorkbook().write(fos);
//                  fos.close();
            }
        } catch (Exception e) {
            CommonResult.success(failWorkbook, "失败数据列表");
        }
//            excelPoiService.insert(list);

        return CommonResult.success(failList);
    }

}
